<?php
use App\Helpers\Ajax;
use App\Models\Merchant;
Use App\Models\Order;
Use App\Models\PayInfo;
Use App\Models\Product;
Use App\Models\SUsers;
use App\Models\Address;
Use App\Models\User;
Use Illuminate\Support\Facades\Log;
Use Illuminate\Support\Str;
use Carbon\Carbon;
use App\Models\Commission;
use Illuminate\Support\Facades\DB;

function getUser($request)
{
    $openid = $request->get('openid');
    return SUsers::where('openid', $openid)->first();
}

/**
 * 获取特定位置的内销商品
 * @param $user_id
 * @param $name
 * @param $cate_id
 * @param $type
 * @return mixed
 */
function getAddressProducts($user_id,$name,$cate_id,$type){
    $address = Address::where('user_id',$user_id)->first();
    $merchants = Merchant::where('province',$address['province'])
        ->where('province',$address['province'])
        ->where('city',$address['city'])
        ->where('district',$address['district'])
        ->where('town',$address['town'])
        ->pluck('id');
    $products = Product::whereIn('merchant_id',$merchants)
        ->where('domestic',1)
        ->where('verify',1)
        ->where('shelves',1)
        ->when($type,function ($query)use($type){
            return $query->where('activity_type',$type);
        })
        ->when($name,function ($query)use($name){
            return $query->where('name','like','%'.$name.'%');
        })
        ->when($cate_id,function ($query)use($cate_id){
            return $query->where('cate_id',$cate_id);
        });


    return $products;
}

/**
 * 定时任务：每秒钟执行一次
 * 未付款订单检测，判断未付款订单是否超时，超时则取消
 */
function checkOrderPayStatus()
{
    $orders = PayInfo::where('platform_status',0)->get();
    foreach ($orders as $order) {
        $carbon = Carbon::parse ($order['created_at']); // 格式化一个时间日期字符串为 carbon 对象
        $int = Carbon::now()->diffInMinutes($carbon, true); // $int 为绝对值
        $user = SUsers::findOrFail($order['user_id']);
        if ($int > 15){
            //超过15分钟的订单取消
            DB::transaction(function ()use ($order,$user){
                $order['platform_status'] = 2;
                $order->saveOrFail();
                Order::where('user_id',$user->id)->where('trade_no',$order['trade_no'])->update(['status'=>5]);
            },5);
            Log::info('====订单超时取消，订单号为：'.$order['id']);
        }
    }
}

/**
 * 检测超过7天未完成的订单，系统自动完成,计算佣金
 */
function checkUnCompletedOrder(){
    $orders = Order::where('status',3)->get();
    foreach ($orders as $order){
        $carbon = Carbon::parse ($order['updated_at']); // 格式化一个时间日期字符串为 carbon 对象
        $int = Carbon::now()->diffInDays($carbon, true); // $int 为绝对值
        if ($int >= 7){
            //超过7天未完成的订单自动完成
            DB::transaction(function ()use ($order){
                $order['status'] = 4;
                $order->saveOrFail();
                Log::info('=====订单自动完成，订单号为：'.$order['id']);
                if ($order['to_user_id'] != -1){
                    $commission = new Commission;
                    $commission['user_id'] = $order['to_user_id'];
                    $commission['from_user_id'] = $order['user_id'];
                    $commission['order_id'] = $order['id'];
                    $commission['status'] = 0;
                    $commission['amount'] = $order['payment'] * 0.1;
                    $commission->saveOrFail();
                    Log::info('=====计算佣金，用户id为：'.$commission['user_id'].',佣金id为:'.$commission['amount']);
                    //把佣金加入到总额
                    $user = SUsers::findOrfail($order['to_user_id']);
                    $user['commission'] += $commission['amount'];
                    $user->saveOrFail();
                }
                },5);

        }
    }
}



/**
 * 检查商品库里面京东商品的价格
 */
function checkJdGoodsPrice()
{
    $ajax = new Ajax();
    $items = Product::where('from', 'like', 'jd-%')->get();
    foreach ($items as $item) {
        $sku = str_replace('jd-', '', $item['from']);
        $result = $ajax->get("https://p.3.cn/prices/mgets?skuIds=J_$sku");
        if (isset($result[0]) && isset($result[0]['p'])) {
            $price = $result[0]['p'];
            $priceArr = explode('.', $price);
            $priceInt = $priceArr[0];
            $priceX = $priceArr[1] / 100;
            Log::info($priceInt * 1.2);
            $item['cost_price'] = $price;
            $item['price'] = $priceX + $priceInt + round($priceInt * 0.3);
            $item['original_price'] = $priceX + $priceInt + round($priceInt * (0.3 + rand(1, 20) / 100));
            $item->save();
        }
    }
}

/**
 * 增加机器人用户
 */
function addRobotUser()
{
    $nicknames = file('nickname.txt');
    foreach ($nicknames as $index => $nickname) {
        $num = $index + 1;
        $user = new SUsers();
        $user['openid'] = Str::random(28);
        $user['session_key'] = Str::random(128);
        $user['merchant_id'] = -1;
        $user['nickname'] = $nickname;
        $user['avatar'] = "/uploads/avatar/$num.jpg";
        $user['is_robot'] = 1;
        $user->save();
    }
}

/**
 * 机器人刷购买记录
 */
function robotBuyProduct()
{
    Log::info("机器人购买记录");
    $url = config('app.url') . '/api/order/place';
    $ajax = new Ajax();
    $products = Product::where('verify', 1)
        ->where('shelves', 1)
        ->where('activity_type', 1)
        ->where('status', 1)
        ->where(function ($q) {
            $q->where('stock', '>', 0)->orWhere('stock', '-1');
        })
        ->inRandomOrder()
        ->take(10)
        ->get();
    $users = SUsers::where('is_robot', 1)->inRandomOrder()->take(1000)->get();
    foreach ($products as $product) {
        $stock = $product['stock'];
        $max = 20; // 每天最大销量
        if ($stock != -1) {
            $max = ceil($stock / 10);
        }
        $rand = $max / (24 * 60) * 100;
        $number = rand(1, 100);
        if ($number < floor($rand)) {
            $user = $users[rand(0, count($users))];
            $merchant = Merchant::find($product['merchant_id']);
            $address = [
                'province' => $merchant['province'],
                'city' => $merchant['city'],
                'district' => $merchant['district'],
                'detail' => $merchant['town'],
                'username' => '机器人' . $user['id'],
                'phone' => '13660167264',
            ];
            $data = [
                'openid' => $user['openid'],
                'address' => $address,
                'products' => [
                    [
                        'id' => $product['id'],
                        'count' => rand(1,3),
                    ]
                ],
                'is_cart' => 0,
                'no_pay' => 1,
            ];
            $result = $ajax->post($url, http_build_query($data));
            Log::info($result);
            $nickname = $user['nickname'];
            $productName = $product['name'];
            Log::info("用户: $nickname 购买了商品：$productName");
        }
    }

}
